package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.User;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.WatchService;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 营业额统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        //当前集合用于存放从begin到end的范围内的时间
//        List<LocalDate> dateList = new ArrayList<>();
//        dateList.add(begin);
//        while (!begin.equals(end)) {
//            begin = begin.plusDays(1);
//            dateList.add(begin);
//        }
        List<LocalDate> dateList = dateList(begin, end);
        //引入lang3包的工具类，将集合转换成String字符串，并用逗号隔开
        String join = StringUtils.join(dateList, ",");

        //存放每天的营业额
        List<Double> turnoverList = new ArrayList<>();
        //查询每天对应的营业额数据
        for (LocalDate date : dateList) {
            //查询date对应的营业额数据，营业额数据是指订单”已完成“的金额统计
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }
        //引入lang3包的工具类，将集合转换成String字符串，并用逗号隔开
        String join1 = StringUtils.join(turnoverList, ",");

        return TurnoverReportVO
                .builder()
                .dateList(join)
                .turnoverList(join1)
                .build();
    }

    /**
     * 日期集合方法
     *
     * @param begin
     * @param end
     * @return
     */
    private List<LocalDate> dateList(LocalDate begin, LocalDate end) {
        //日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        return dateList;
    }


    /**
     * 用户统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        //日期
//        List<LocalDate> dateList = new ArrayList<>();
//        dateList.add(begin);
//        while (!begin.equals(end)) {
//            begin = begin.plusDays(1);
//            dateList.add(begin);
//        }
        List<LocalDate> dateList = dateList(begin, end);

        //用户总量
        List<Integer> totaluserList = new ArrayList<>();
        List<Long> userIdList = new ArrayList<>();
        Map map = new HashMap();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            map.put("end", endTime);
            Integer userSum = orderMapper.getByCreatTime(map);
            //新增用户
            map.put("begin", beginTime);
            Long userIdSum = orderMapper.getUserId(map);
            userIdList.add(userIdSum);
            totaluserList.add(userSum);
        }

        //封装结果数据
        return UserReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalUserList(StringUtils.join(totaluserList, ","))
                .newUserList(StringUtils.join(userIdList, ","))
                .build();
    }

    /**
     * 订单统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        //日期
        List<LocalDate> dateList = dateList(begin, end);

        //每天的订单数
        List<Integer> orderCountList = new ArrayList<>();
        //每日有效订单数
        List<Integer> validOrderCountList = new ArrayList<>();


        Map map = new HashMap<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            map.put("end", endTime);
//            //订单总数
//            Integer totalOrderCount = orderMapper.getTotalOrderCount(map);
            map.put("begin", beginTime);
            //每天的订单数
            Integer orderCount = orderMapper.getDailyOrderCount(map);
            //每天有效订单数
            map.put("status", Orders.COMPLETED);
            Integer dailyValidOrderCount = orderMapper.getDailyValidOrderCount(map);
            validOrderCountList.add(dailyValidOrderCount);
            orderCountList.add(orderCount);
//            //有效订单数
//            Integer validOrderCount = orderMapper.getValidOrderCount(map);


        }

        //时间区间内订单总数
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();

        //时间区间内有效订单数
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();

        //订单完成率
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0) {
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }

        //封装结果数据
        return OrderReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 销售前十排名
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
//        //商品名称列表
//        List<String> nameList = new ArrayList<>();
//        //销量列表
//        List<Integer> numberList = new ArrayList<>();
//        Map map = new HashMap();
//        for (LocalDate date : dateList(begin, end)) {
//            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
//            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
//            map.put("begin", beginTime);
//            map.put("end", endTime);
//            map.put("status", Orders.COMPLETED);
//            //查询订单id
//            List<Long> orderIdList = orderMapper.getByOrderId(map);
//            for (Long orderId : orderIdList) {
//                //根据订单id查询菜品名称
//                List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orderId);
//                for (OrderDetail orderDetail : orderDetailList) {
//                    for (String s : nameList) {
//                        if (!s.equals(orderDetail.getName())) {
//                            nameList.add(orderDetail.getName());
//                        }
//                    }
//                }
//                //根据nameList中的菜品名称查询该菜品销量
//                for (String dishName : nameList) {
//                    Integer number = orderDetailMapper.getByDishName(dishName,orderId);
//                    numberList.add(number);
//                }
//            }
//        }
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);
        List<String> names = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String nameList = StringUtils.join(names, ",");

        List<Integer> numbers = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        //封装结果数据
        return SalesTop10ReportVO
                .builder()
                .nameList(nameList)
                .numberList(StringUtils.join(numbers, ","))
                .build();
    }

    /**
     * 导出Excel报表接口
     *
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        //1.查询数据库获取营业数据--30天数据
        //开始时间--30天前
        LocalDate begin = LocalDate.now().minusDays(30);
        //结束时间--昨天
        LocalDate end = LocalDate.now().minusDays(1);


        BusinessDataVO businessDataVO = workspaceService.businessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));

        //2.通过POI将数据写入到模板Excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        //基于模板文件创建一个新的Excel文件
        try {
            XSSFWorkbook excel = new XSSFWorkbook(in);
            //向模板填充数据
            //获取表格Sheet页
            XSSFSheet sheet1 = excel.getSheet("Sheet1");

            //时间数据
            sheet1.getRow(1).getCell(1).setCellValue("时间:" + begin + "至" + end);

            //概览数据填充
            //获取第四行
            XSSFRow row = sheet1.getRow(3);
            //营业额
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            //订单完成率
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            //新增用户数
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());

            //获取第五行
            row = sheet1.getRow(4);
            //有效订单
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            //平均客单价
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            //明细数据填充--30天
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                //查询某一天的营业数据
                BusinessDataVO businessData = workspaceService.businessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                //填充第i+8行
                row = sheet1.getRow(i+7);
                //时间
                row.getCell(1).setCellValue(String.valueOf(date));
                //营业额
                row.getCell(2).setCellValue(businessData.getTurnover());
                //有效订单
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                //订单完成率
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                //新增用户
                row.getCell(6).setCellValue(businessData.getNewUsers());
                //平均客单价
                row.getCell(5).setCellValue(businessData.getUnitPrice());
            }

            //3.通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭资源
            out.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }



    }
}
